package cyc2018.二分查找.原理;

import java.util.Arrays;

/**
 * 在排序数组中查找元素的第一个和最后一个位置
 */
public class Test34 {

    public static int[] searchRange(int[] nums, int target) {
        int start = -1;
        int end = -1;
        // 1. 找到 target 在数组里面第一次出现的位置
        int targetIndex = getTargetIndex(nums, target);
        if (targetIndex != -1) {
            // 2. 然后从这个位置往两边扩散寻找 target 的边界
            for (end = targetIndex; end < nums.length; end++) {
                if (nums[end] != target) {

                    break;
                }
            }
            for (start = targetIndex; start >= 0; start--) {
                if (nums[start] != target) {

                    break;
                }
            }
            // 收缩数据
            if (end != targetIndex) {
                end--;
            }
            if (start != targetIndex) {
                start++;
            }
        }
        return new int[]{start, end};
    }

    public static int getTargetIndex(int[] nums, int target) {
        int start = 0;
        int end = nums.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] > target) {
                end = mid - 1;
            } else {
                start = mid + 1;
            }
        }
        return -1;
    }

    public static void main(String[] args) {
        int[] nums = {5,7,7,8,8,10};
//        int[] nums = {1};
        int target = 8;
        int[] ans = searchRange(nums, target);
        System.out.println(Arrays.toString(ans));
    }
}
